<template>
  <div class="page">
    <StoreChoice
      ref="suitShops"
      :current="coupon.suitShops"
      :multipleChoice="$route.query.id!=2"
      @listenToStoreSelect="getSelectStoreValue"
      :statusFilter="false"
      :hasTotal="false"
    />
    <StoreChoice
      ref="grantShops"
      :current="coupon.grantShops"
      :multipleChoice="true"
      @listenToStoreSelect="getSelectStoreValue"
      :statusFilter="false"
      :hasTotal="false"
    />
    <messageComfirm leftText="已入驻" rightText="去入驻" @leftCallBack="handLeft" @rightCallBack="handleRight" :visible="modalVisible">
      <div class="m-comfirm">
        <div class="m-comfirm_title">使用券营销功能的门店需要入驻“享惠达人”小程序</div>
        <div class="m-comfirm_logo"></div>
      </div>
    </messageComfirm>
		<couponSetting ref="couponSetting" :config="coupon" @consume="consume"/>
		<mt-datetime-picker
			ref="startPicker"
			type="date"
			v-model="startDate"
			year-format="{value} 年"
			month-format="{value} 月"
			date-format="{value} 日"
			confirmText="下一步" 
			:startDate="new Date()"
			@confirm="$refs.endPicker.open()"
			@cancel="handleCancel"
		></mt-datetime-picker>
		<mt-datetime-picker
			ref="endPicker"
			type="date"
			v-model="endDate"
			year-format="{value} 年"
			month-format="{value} 月"
			date-format="{value} 日"
			:startDate="moment(startDate).toDate()"
			:endDate="moment(startDate).add(365, 'day').toDate()"
			@confirm="dateChoice"
			@cancel="handleCancel"
		></mt-datetime-picker>
		<mt-actionsheet :actions="actions" v-model="actionVisible"></mt-actionsheet>
		<awesome-picker ref="picker" v-if="pickerVisible" :textTitle="picker.title" :data="picker.data" :anchor="picker.anchor" @confirm="(v)=>handleConfirm(v)"></awesome-picker>
    <div class="scroll-view coupon-view">
      <customHeader class="page-header" :middleTitle="['满减券','消费赠券','拉新券','引流券'][$route.query.id-1]+'创建'" rightTitle="高级设置" @rightCallBack="$refs.couponSetting.popupShow()"/>
			<div class="scroll-view">
				<div class="page-body">
					<div class="coupon-card">
						<div class="coupon-tag">{{['满减券','消费赠券','拉新券','引流券'][$route.query.id-1]}}</div>
						<div class="coupon-card-l">
							<div class="parValue" v-html="parValue"></div> 
							<p class="mt20 f24">满{{coupon.useLimit}}元可用</p>
						</div>
						<div class="coupon-card-r">
							<div class="coupon-card-name f36">{{couponTitle}}</div>
							<div class="mt20 f24">有效期：{{parTime}}</div>
						</div>
					</div>
					<div class="coupon-title">券设置<span>基于门店数据，为您推荐了更能吸引顾客的券{{['面额','折扣'][coupon.voucherType-1]}}</span></div>
					<ul class="form-style">
						<li>
							<span>券名称</span>
							<div>
								<inputClear warpClass="t-r" @blur="fieldValidate('voucherName')" v-model="coupon.voucherName" :limitVal="(v)=>v.trim()" :placeholder="couponTitle" :maxlength="24"/>
							</div>
						</li>
						<li @click="showPicker('couponType')">
							<span>优惠类型</span>
							<div>{{['优惠券','折扣券'][coupon.voucherType-1]}}<i class="zhk-list_rarrow"></i></div>
						</li>
						<li v-if="coupon.voucherType==1">
							<span>券面额</span>
							<div class="t5">
                <inputClear warpClass="t-r" v-model="coupon.facePrice" @blur="limitMin('facePrice',0.01)" :limitVal="(v)=>limitFunc(v,999)"/>
                <span class="pl15">元</span>
              </div>
						</li>
						<li v-if="coupon.voucherType==2">
							<span>券折扣</span>
							<div class="t5">
                <inputClear warpClass="t-r" v-model="coupon.discount" @blur="limitMin('discount',0.1)" :limitVal="(v)=>limitFunc(v,9.9)"/>
                <span class="pl15">折</span>
              </div>
						</li>
						<li>
							<span>使用门槛</span>
							<div class="t5">实付满<inputClear :size="true" v-model="coupon.useLimit" @blur="limitMin('useLimit',0.01)" :limitVal="(v)=>limitFunc(v,99999999)"/>元可用</div>
						</li>
						<li @click="actionVisible=true">
							<span>券有效期</span>
							<div>{{parTime}}<i class="zhk-list_rarrow"></i></div>
						</li>
						<li v-if="$route.query.id==2">
							<span>发放条件</span>
							<div class="t5">实付满<inputClear :size="true" v-model="coupon.grantLimit" @blur="limitMin('grantLimit',0.01)" :limitVal="(v)=>limitFunc(v,99999999)"/>元就返</div>
						</li>
						<li v-if="$route.query.id==3">
							<span>发放人群</span>
							<div>新客</div>
						</li>
            <li @click="handleClickSelectStore('grantShops')" v-if="$route.query.id!=2">
							<span>发放门店</span>
							<div>{{grantShopsDesc}}<i class="zhk-list_rarrow" v-if="!isSingleStore"></i></div>
						</li>
            <li @click="handleClickSelectStore('suitShops')" v-if="$route.query.id!=2">
							<span>适用门店</span>
							<div>{{suitShopsDesc}}<i class="zhk-list_rarrow" v-if="!isSingleStore"></i></div>
						</li>
            <li @click="handleClickSelectStore('suitShops')" v-if="$route.query.id==2">
							<span>适用门店</span>
							<div>
                {{isSingleStore ? roleInfo.shopName: (coupon.suitShops.length?coupon.suitShops[0].selectName:'请选择')}}
                <i class="zhk-list_rarrow" v-if="!isSingleStore"></i>
              </div>
						</li>
					</ul>
				</div>
				<mt-button class="w100" :disabled="!submitStatus" @click="submit" type="primary">确认发布</mt-button>
			</div>
    </div>
  </div>
</template>

<script>
import moment from "moment";
import {Toast, DatetimePicker} from 'mint-ui';
import Vue from "vue";
import AwesomePicker from "vue-awesome-picker";
Vue.use(AwesomePicker);
import customHeader from "@/components/header/header";
import inputClear from "@/components/inputClear/inputClear";
import StoreChoice from "@/components/StoreChoice/StoreChoice";
import messageComfirm from "@/components/messageComfirm/messageComfirm";
import couponSetting from "./couponSetting";

export default {
	components: {
		inputClear,
    customHeader,
    StoreChoice,
    messageComfirm,
		couponSetting
  },
	data() {
		return {
      modalVisible: false,
      moment: moment,
			startDate: new Date(),
      endDate: new Date(),
			actions: [{
				name: '固定日期',
        method: () => {
					this.showPicker('time')
				}
			}, {
				name: '自定义日期',
        method: () => {
					this.$refs.startPicker.open();
				}
			}],
      actionVisible: false,
      pickerVisible: false,
			picker: {
        anchor: [],
        data: []
      },
			couponType: {
        anchor: [0],
        title: "优惠类型",
        data: [["优惠券","折扣券"]]
      },
			time: {
        anchor: [0],
        title: "固定日期",
        data: [[3, 5, 7, 15, 30, 60, 180]]
      },
			submitStatus: true,
			coupon: {
        marketType: 1,  //营销类型 1:场景营销 2:团购营销
				voucherName: '',//券名称
				voucherType: 1, //券优惠类型 1:优惠券 2:折扣券
        grantShops: [], //发放门店列表
        suitShops: [],  //适用门店列表
        activityStartTime: Date.now(), //活动开始时间
        activityEndTime: moment(this.activityStartTime).add(20, 'years').valueOf(), //活动结束时间
        effectiveType: 1, //有效期类型 1:固定时间有效，2:指定日期内有效
        effectiveStartTime: '', //券生效起始时间
        effectiveEndTime: '', //券生效结束时间
        validityPeriod: 30, //固定时间,单位天
        facePrice: '', //券面额
        discount: '',  //券折扣
        useLimit: 10,  //使用门槛 满10元可用
        marketActivityType: 1, //营销活动类型 1:满减券 2:消费赠券 3:拉新券 4:引流券'
        marketType: 1, //营销类型 1:场景营销 2:团购营销
        //grantLimit:  //消费赠券-发放门槛 实付满10元就返
        //grantType: 1,//拉新券-发放人群 1:新客
        inventory: -1,
        activityType: 1,
      },
      suitShopsAll: true,
      grantShopsAll: true,
			initial: {
				discount: 8,
				facePrice: 3,
				useLimit: 15,
				grantType: 1,
				grantLimit: 0.01
      },
      store: [],
      roleInfo: {}
		}
	},
	computed: {
    couponTitle() {
      let txt = '';
      if(this.coupon.voucherName) {
        txt = this.coupon.voucherName;
      }else {
        /* if(this.roleInfo.manyShopFlag!==undefined && !this.roleInfo.manyShopFlag) {
          txt = this.roleInfo.shopName;
        }else {
          txt = this.store.length ? this.store[0].shopName.substr(0,21) : '';
        }
        txt += ['优惠券','折扣券'][this.coupon.voucherType-1]; */
        txt = this.roleInfo.shopName + ['优惠券','折扣券'][this.coupon.voucherType-1];
      }
      return txt;
    },
		parValue() {
      let num = this.coupon.voucherType==1 ? this.coupon.facePrice : this.coupon.discount;
      let arr = (''+num).split('.');
      let html = arr.length==1 ? `<strong>${arr[0]}</strong>` : `<strong>${arr[0]}</strong>.${arr[1]}`;
      return this.coupon.voucherType==1 ? `<span>¥</span>${html}` : html+'<span>折</span>';
		},
		parTime() {
      let txt = '';
      if(this.coupon.effectiveType==1) {
        txt = `领取后${this.coupon.validityPeriod}天` ;
      }else {
        txt = `${moment(this.coupon.effectiveStartTime).format('YYYY-MM-DD')} 至 ${moment(this.coupon.effectiveEndTime).format('YYYY-MM-DD')}`
      }
      return txt;
    },
    suitShopsDesc() {
      return this.getStoreName('suitShops')
    },
    grantShopsDesc() {
      return this.getStoreName('grantShops')
    },
    isSingleStore() {
      if(this.roleInfo) {
        return this.roleInfo.manyShopFlag!==undefined && !this.roleInfo.manyShopFlag
      }
      return false;
    }
	},
	methods: {
    handLeft() {
      this.modalVisible = false;
      Toast('发布成功');
      this.$router.push({path: '/couponMarketing/couponManage?stack=2'});
    },
    handleRight() {
      this.modalVisible = false;
      this.$router.push({path: "/selectMiniAppType"});
      // this.$router.push({path: "/selectMiniAppType/selfMiniAppManage"});
    },
    getStoreName(key) {
      let txt = "", store = this.coupon[key], isAll = this[key+'All'];
      if(this.roleInfo.manyShopFlag!==undefined && !this.roleInfo.manyShopFlag) {
        txt = this.roleInfo.shopName;
      }else if(!isAll) {
        if(store.length === 1) {
          txt = store[0].selectName;
        }else {
          txt = store.length ? `已选择${store.length}家门店` : '全部门店';
        }
      }else {
        txt = "全部门店";
      }
      return txt;
    },
    getSelectStoreValue(value, storeName) {
      if(!this.currentKey) return;
      let key = this.currentKey+'All';
      if(storeName === "全部门店") {
        this[key] = true;
      }else {
        this[key] = false;
      }
      if(this.$route.query.id==2) {
        this.coupon.suitShops = this.coupon.grantShops = value;
      }else {
        this.coupon[this.currentKey] = value;
      }
      this.currentKey = null;
    },
    handleClickSelectStore(key) {
      if(this.roleInfo.manyShopFlag!==undefined && !this.roleInfo.manyShopFlag){
        return;
      }
      this.currentKey = key;
      this.$refs[key].popupShow();
    },
    consume(params) {
      this.coupon = Object.assign({}, this.coupon, params);
    },
    dateChoice(e) {
      this.coupon.effectiveType = 2;
      this.coupon.effectiveStartTime = moment(+this.startDate).startOf('day').valueOf();
      this.coupon.effectiveEndTime = moment(+this.endDate).endOf('day').valueOf();
    },
    handleCancel() {
      this.startDate = this.endDate = new Date();
    },
		limitMin(key, min) {
			if(this.coupon[key]=='') {
				this.coupon[key] = this.initial[key];
			}else if(this.coupon[key]<min) {
				this.coupon[key] = min;
			}
		},
		limitFunc(v, max) {
			let reg = new RegExp(`\\d{1,}\\.{0,1}\\d{0,${max==9.9?1:2}}`);
			let val = v.replace(/^0{2,}/,'0').replace(/^0[\d]/,'0').match(reg);
			val = val && val.length ? val[0] : '';
			if(+val>max) val = max;
			return val;
		},
		showPicker(key) {
      this.currentKey = key;
      this.picker = this[key];
			this.pickerVisible = false;
			this.$nextTick(()=> {
				this.pickerVisible = true;
				this.$nextTick(()=> {
					this.$refs.picker.show();
				});
			});
    },
    handleConfirm(v) {
      this.picker.anchor = v;
      if(this.currentKey=='time') {
        this.coupon.effectiveType = 1;
        this.coupon.validityPeriod =  v[0].value;
      }
			if(this.currentKey=='couponType') {
        this.coupon.voucherType = v[0].index+1;
      }
    },
		fieldValidate(fieldName, field) {
			let isValidate = true;
			if(fieldName) {
        this.checkFiled(fieldName, this.coupon[fieldName])
      }else {
				let fileds = ['voucherName','suitShops','grantShops'];
        for(let i=0; i < fileds.length; i++) {
          isValidate = this.checkFiled(fileds[i], field[fileds[i]])
          if(!isValidate) break;
        }
        return isValidate;
      }
    },
		checkFiled(key, value) {
      const fildRule = {
        voucherName: {
          required: true,
          reg: /^[\u4e00-\u9fa5a-zA-Z0-9(),（），*.\-_|]{1,24}$/,
          emptyMsg: '请填写券名称',
          errMsg: '券名称仅可填写汉字,大小写字母,数字,中英文括号，中英文逗号，星号，英文句号，下划线，中杠，间隔号'
        },
        grantShops: {
          required: true,
          emptyMsg: '请选择发放门店'
        },
        suitShops: {
          required: true,
          emptyMsg: '请选择适用门店'
        }
			}
      let rule = fildRule[key], validate = true;
      this.toastInstance && this.toastInstance.close();
      if(rule.required && CommonUtil.isEmpty(value)) {
        this.toastInstance = Toast(rule.emptyMsg);
        validate = false;
      }else if(value && rule.reg) {
        validate = (rule.reg).test(value);
        if(!validate) {
          this.toastInstance = Toast(rule.errMsg);
        }
      }
			return validate;
    },
    //查询所有门店的接口
    allShopId() {
      this.ajax({
        url: "/newapp/reconciliation/getAllShop.do",
        type: "get",
        controlLoading: true
      }).then(res => {
        if(res.success) {
          let store = res.resultObject, _store = [];
          this.roleInfo.shopName = store.length ? store[0].mainShopName : '';
          store.forEach(item=>{
            _store.push({
              shopId: item.shopId,
              shopName: item.shopName,
            });
          })
          this.store = _store;
        }
      });
    },
    formatStore(store) {
      let _store = [];
      if(this.isSingleStore) {
        return this.store.slice(0);
      }
      store.length && store.forEach(item=> {
        _store.push({
          shopId: item.selectKey,
          shopName: item.selectName
        })
      })
      return store.length ? _store : (this.$route.query.id!=2 ? this.store.slice(0) : []);
    },
		submit() {
      Object.keys(this.initial).forEach(key=> {
        if(this.coupon[key]=='') {
          this.coupon[key] = this.initial[key];
        }
      });
      let params = Object.assign({}, this.coupon);
      params.suitShops = this.formatStore(params.suitShops);
      params.grantShops = this.formatStore(params.grantShops);
      delete params.activityType;
      if(params.voucherType==1) {
        delete params.discount;
      }else {
        delete params.facePrice;
      }
      if(params.effectiveType==1) {
        delete params.effectiveStartTime;
        delete params.effectiveEndTime;
      }else {
        delete params.validityPeriod;
      }
      let validate = this.fieldValidate(null, params);
      if(!validate) return;
      this.submitStatus = false;
      this.ajax({
        type: "post",
        url: "/newapp/activity/create.do",
        data: params,
        controlLoading: true
      }).then(res => {
        if(res.success) {
          // this.$router.push({path: '/couponMarketing/couponManage?stack=2'});
          this.submitStatus = true;
          this.modalVisible = true;
        }else {
          Toast(res.msg);
          this.submitStatus = true;
        }
      }).catch(err=> {
        this.submitStatus = true;
      })
		}
  },
  created() {
    this.coupon.marketActivityType = this.$route.query.id;
		if(this.$route.query.id!=2) {
			this.$delete(this.initial, 'grantLimit')
		}else if(this.$route.query.id!=3) {
			this.$delete(this.initial, 'grantType')
    }
    if(this.$route.query.id==2) {
      this.coupon.activityType = 0;
      this.coupon.activityStartTime = moment().startOf('day').valueOf();
      this.coupon.activityEndTime = moment().add(89, 'day').endOf('day').valueOf();
    }
    if(this.$route.query.activityId) {
      Object.keys(this.coupon).forEach(key=> {
        if(this.$route.query[key]) this.coupon[key] = this.$route.query[key];
        if(this.$route.query.id==2) this.coupon.grantLimit = this.$route.query.grantLimit;
      }); 
      let grantShops = [], suitShops = [];
      this.coupon.grantShops.forEach(item=> {
        grantShops.push({
          selectKey: item.shopId,
          selectName: item.shopName
        });
      });
      this.coupon.grantShops = grantShops;
      this.coupon.suitShops.forEach(item=> {
        suitShops.push({
          selectKey: item.shopId,
          selectName: item.shopName
        });
      });
      this.coupon.suitShops = suitShops;
      this.suitShopsAll = false;
      this.grantShopsAll = false;
      // this.coupon.activityType = +(moment(this.coupon.activityStartTime).add(20, 'years').valueOf() == this.coupon.activityEndTime);
      this.coupon.activityType = +(moment(this.coupon.activityEndTime).year()-moment(this.coupon.activityStartTime).year()>18)
    }else {
      this.coupon = Object.assign({}, this.coupon, this.initial);
    }
    CommonUtil.getUserInfo(true).then(data => {
      this.roleInfo = data;
      if(data.manyShopFlag!==undefined && !data.manyShopFlag) {
        this.store = [{
          shopId: data.yzShopId,
          shopName: data.shopName
        }];
      }else {
        this.allShopId();
      }
    });
  }
}
</script>

<style lang="scss" scoped>
@import "../../style/public";
.m-comfirm {
  &_title {
    text-align: center;
    @include remCalc(padding, 30, 80);
    @include remCalc(font-size, 30);
  }
  &_logo {
    display: block;
    text-align: center;
    @include remCalc(margin, 0, auto, 50);
    @include remCalc(width, 120);
    @include remCalc(height, 120);
    background-image: url('../../../static/images/xhdr.png');
    background-size: contain;
  }
}
.pl15 {
  @include remCalc(padding-left, 15);
}
.page-header /deep/ .right {
  color: #333;
}
.t5 /deep/ .input-clear-wrap {
  position: relative;
  @include remCalc(top, 2);
}
.coupon {
	&-card {
		position: relative;
		background-color: #fff;
		box-shadow: 0 .01rem .1rem 0 rgba(0,0,0,.1);
		font-weight: bold;
		color: #95710F;
		@include remCalc(border-radius, 10);
    @include remCalc(margin, 30, 30, 50);
    @include remCalc(min-height, 220);
    @include remCalc(padding-top, 30);
    box-sizing: border-box;
		&-l {
			float: left;
			align-items: center;
      @include remCalc(width, 198);
      @include remCalc(margin-right, 30);
      text-align: center;
			position: relative;
			&:after {
				content: ' ';
				display: block;
				position: absolute;
				border: 1px dashed #95710F;
        @include remCalc(right, -5);
				@include remCalc(top, 10);
				@include remCalc(bottom, 0);
			}
		}
		&-r {
			@include remCalc(padding, 0, 30);
    }
    &-name {
      @include remCalc(height, 100);
      word-break: break-all;
    }
	}
	&-tag {
    position: absolute;
    top: 0;
		color: #fff;
		background-color: #95710F;;
		@include remCalc(height, 44);
		@include remCalc(line-height, 44);
		@include remCalc(font-size, 24);
		@include remCalc(padding, 0, 20);
		@include remCalc(border-radius, 10, 0, 10, 0);
	}
	&-title {
		color: #333;
		background-color: #fff;
		@include remCalc(font-size, 32);
		@include remCalc(padding, 25, 30);
		span {
			color: #666;
			@include remCalc(font-size, 20);
			@include remCalc(margin-left, 10);
		}
	}
}
</style>
<style lang="scss">
@import "../../style/public";
.parValue {
  @include remCalc(font-size, 36);
  @include remCalc(height, 100);
  @include remCalc(line-height, 120);
	strong {
    @include remCalc(font-size, 75);
    font-weight: normal;
	}
	span {
		font-weight: normal;
		@include remCalc(font-size, 28);
		@include remCalc(padding, 0, 5);
	}
}
.t-r {
	text-align: right!important;
}
</style>